<?php
namespace common\component;


use yii\base\Exception;
use yii\data\Pagination;
use yii\db\ActiveRecord;
use yii\db\Query;

class BaseActiveRecord extends ActiveRecord
{
    public $ui=[];

    private $logAttributes = [];

    private $logedKey = [];

    /**
     * example:
     *  $q = static::find()->where(['grade'=>$depath]);
     *  $data = self::arrListByPage(0, 0, $q);  为0时显示全部 否则 按 分页来
     * 按query类条件，返回分页数据
     * @param Query $q 查询条件类
     * @param integer $page 页码 为 0时显示全部
     * @param integer $pageSize 数据数
     * @author t.young
     * @return array
     */
    public static function arrListByPage(Query $q,$page,$pageSize){
        $return = ['total'=>0,'rows'=>[]];
        if ($page < 1 || $pageSize < 1){
            $query = $q->all();
            if (empty($query)){
                $return['total'] = 0;
                $return['rows'] = [];
            }
            else{
                $return['total'] = $q->count();
                foreach ($query as $val){
                    if (is_array($val)){
                        $return['rows'][] = $val;
                    }
                    else{
                        $return['rows'][] = $val->getAttributes();
                    }
                }
            }
        }
        else{
            if ($pageSize > 1){
                $q2 = clone $q;
                $count = $q2->count();
            }
            else{
                $count = 1;
            }
            if ($count < 1){
                $return = ['total'=>0,'rows'=>[]];
            }
            else{
                if ($page < 1){
                    $page = 0;
                }
                else{
                    $page = $page -1;
                }
                $offset = $page * $pageSize;
                if ($offset >= $count){
                    $return = ['total'=>$count,'rows'=>[]];
                }
                else{
                    $q->offset = $offset;
                    $q->limit = $pageSize;
                    $query = $q->all();
                    if (empty($query)){
                        $count = 0;
                    }
                    $return['total'] = (int)$count;
                    $return['rows'] = [];
                    foreach ($query as $val){
                        if (is_array($val)){
                            $return['rows'][] = $val;
                        }
                        else{
                            $return['rows'][] = $val->getAttributes();
                        }
                    }
                }
            }
        }
        return $return;
    }

    /**
     * 加载组装分页数据
     */
    public function table($query,$params=[]) {

        //页码的处理
        if(isset($_POST['page'])){
            $_GET['page']=$_POST['page'];
        }
        $countQuery = clone $query;
        $pageSize = isset($params['pageSize'])?$params['pageSize']:\Yii::$app->params['pageSize'];
        $pages = new Pagination(['totalCount'=>$countQuery->count(),'pageSize'=>$pageSize,'defaultPageSize'=>$pageSize]);
        $hasMorePage = true;
        if (isset($params['page'])) {
            if ((intval($params['page'])-1) * $pages->defaultPageSize > $pages->totalCount) {
                $hasMorePage = false;
            }
        }

        $models = [];
        if ($hasMorePage) {
            $arrSort = [];
            if (!empty($params['sort'])) {
                $sortColmn = explode(',',$params['sort']);
                $sortOrder = explode(',',$params['order']);
                foreach ($sortColmn as $key => $item) {
                    $arrSort[$item] = $sortOrder[$key] == SORT_ASC ? SORT_ASC : SORT_DESC;
                }
            }
           $models = $query->orderBy($arrSort)->offset($pages->offset)->all();
        }
        return ['pages'=>$pages,'models'=>$models];
    }

    /**
     * 获取验证错误信息
     * @param bool $single
     * @return String
     */
    public function getErrorsToString($single = true) {
        $errors = $this->getErrors();
        $errString = "";
        if (count($errors)) {
            foreach ($errors as $key => $errs) {
                if ($single) {
                    $errString = $errs[0];
                    break;
                } else {
                    foreach ($errs as $err) {
                        $errString .= $err;
                    }
                }
            }
        }
        else {
            $errString = "系统异常错误";
        }
        return $errString;
    }

    public function save($runValidation = true, $attributeNames = null)
    {
        $flag = parent::save($runValidation, $attributeNames);
        return $flag;
    }


    public function delete()
    {
        $flag = parent::delete();
        return $flag;
    }

    /**
     * 添加操作日志
     */
    private function logging() {
        //判断当前地址是否需要写操作日志
        if ($this->needLogger()) {
            try{
                \Yii::$app->opLog->logging($this->logAttributes);
            }catch (Exception $e) {
                return false;
            }
            return true;
        }
        return false;
    }

    /**
     * 判断是否需要写操作日志
     */
    private function needLogger() {
        if (!\Yii::$app->controller->allowLog) return false;
        $uri = strtolower(\Yii::$app->controller->getRoute());
        if (!in_array(md5($uri),$this->logedKey) && \Yii::$app->opLog->auth($uri)) {
            $this->logedKey[] = md5($uri);
            return true;
        }
        return false;
    }


}